package com.ybear.patsdk.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.arch.core.util.Function;
import androidx.core.util.Consumer;

import com.ybear.patsdk.utils.Utils;
import com.ybear.ybcomponent.widget.shape.ShapeImageView;

/**
 * 拍一拍图片控件
 * 为了节约时间，这里继承 {@link ShapeImageView} 实现圆角功能
 */
public class PatView extends ShapeImageView {
    private ValueAnimator mValAnim;

    private float mPatPower = 8;
    private int mPatCount = 3;
    private long mIntervalMillis = 5000;
    private long mCurrentMillis = 0;
    private long[] mVibratorTimings;
    private boolean mEnablePat = true;
    private boolean mEnableVibrator = true;
    private boolean mEnableDoubleTouch = true;
    private Consumer<Boolean> mDoubleTouchCall;
    private Function<View, Boolean> mOnPatClickListener;

    public PatView(Context context) {
        this(context, null);
    }

    public PatView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PatView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if( ev.getAction() == MotionEvent.ACTION_UP ) {
            //处理双击事件
            Utils.doubleTouch( 800, mDoubleTouchCall );
        }
        return super.dispatchTouchEvent( ev );
    }

    private void init() {
        //圆形控件
        setShape( Shape.OVAL );
        setFocusable( true );
        setClickable( true );
        mValAnim = new ValueAnimator();
        //震动时间
        mVibratorTimings = new long[] { 0, 50, 150, 50 };
        build();
        initListener();
    }

    private void initListener() {
        //动画更新事件监听器
        mValAnim.addUpdateListener(anim -> {
            float val = (float) anim.getAnimatedValue();
            //左右旋转
            setRotation( val );
            //左右移动
            setTranslationX( val );
        });

        //双击事件监听器
        mDoubleTouchCall = isTouch -> {
            if( mEnableDoubleTouch && isTouch ) {
                //回调拍一拍点击事件监听器
                if( mOnPatClickListener != null ) {
                    //返回true时开始拍一拍
                    if( mOnPatClickListener.apply( this ) ) startPat();
                }else {
                    //开始拍一拍
                    startPat();
                }
            }
        };
    }

    /**
     * 摆幅强度
     * @param mPatPower     强度
     * @return              this
     */
    public PatView setPatPower(float mPatPower) {
        this.mPatPower = mPatPower;
        return this;
    }

    /**
     * 摆幅次数
     * @param mPatCount     次数
     * @return              this
     */
    public PatView setPatCount(int mPatCount) {
        this.mPatCount = mPatCount;
        return this;
    }

    /**
     * 震动时间
     * @param timings       时间。[0]：震动延迟、[1]：震动时长、[2]：震动延迟、[3]：震动时长...
     * @return              this
     */
    public PatView setVibratorTimings(long[] timings) {
        mVibratorTimings = timings;
        return this;
    }

    /**
     * 拍一拍间隔
     * @param millis        毫秒
     */
    public void setIntervalMillis(long millis) { mIntervalMillis = millis; }

    /**
     * 是否启用拍一拍
     * @param enable        是否启用
     */
    public void setEnablePat(boolean enable) { mEnablePat = enable; }

    /**
     * 是否启用震动
     * @param enable        是否启用
     */
    public void setEnableVibrator(boolean enable) { mEnableVibrator = enable; }

    /**
     * 是否启用双击点击
     * @param enable        是否启用
     */
    public void setEnableDoubleTouch(boolean enable) { mEnableDoubleTouch = enable; }

    /**
     * 拍一拍点击事件监听器
     * @param l             监听器
     */
    public void setOnPatClickListener(Function<View, Boolean> l) { mOnPatClickListener = l; }

    /**
     * 构建设置
     */
    public void build() {
        float[] val = new float[ ( mPatCount * 2 ) + 1 ];
        for (int i = 0; i < val.length; i++) {
            if( i < val.length - 1 ) {
                //左右摆幅（ -5, 5, -5, 5 ）
                val[ i ] = i % 2 == 0 ? -mPatPower : mPatPower;
            }else {
                //最后一帧复位
                val[ i ] = 0;
            }
        }
        mValAnim.setFloatValues( val );
    }

    /**
     * 拍一拍
     */
    public void startPat() {
        //是否启用 和 间隔检查
        if( !mEnablePat || !checkInterval() ) return;

        //拍一拍动画
        mValAnim.start();
        //设置震动
        if( mEnableVibrator ) {
            Utils.startVibrator( getContext(), -1, mVibratorTimings );
        }
    }

    /**
     * 间隔检查
     * @return      间隔是否超时
     */
    private boolean checkInterval() {
        if( mIntervalMillis <= 0 ) return true;
        //间隔时间初始化
        if( mCurrentMillis == 0 ) mCurrentMillis = System.currentTimeMillis() - mIntervalMillis;
        //在间隔时间内
        if( mCurrentMillis + mIntervalMillis > System.currentTimeMillis() ) {
            return false;
        }
        mCurrentMillis = System.currentTimeMillis();
        return true;
    }
}
